package com.alan.libapi.api;

import com.alan.libapi.api.Impl.PackageHelper;
import com.alan.library.allog.KLog;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * @className: ALTcpSocketHelper
 * @describtion: ALTcpSocketHelper
 * @author: AlanWang
 * @email: 850267876@qq.com
 * @time: 2016/4/28 09:48
 */
public class ALTcpSocketHelper implements IALSocket {

    private static final int SOCKET_CONNECT_TIMEOUT_DEFAULT = 5*1000;
    private int connetTimeOut = SOCKET_CONNECT_TIMEOUT_DEFAULT;
    private PackageHelper packageHelper;
    private Socket mSocket;
    private String hostIp;
    private int port;

    public ALTcpSocketHelper(String hostIp, int port) {
        super();
        this.hostIp = hostIp;
        this.port = port;
        packageHelper = new PackageHelper();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return mSocket.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return mSocket.getOutputStream();
    }

    @Override
    public boolean sendData(byte[] data) throws IOException {
        return packageHelper.request(getOutputStream(), data);
    }

    @Override
    public byte[] receiveData() throws Exception {
        return packageHelper.response(getInputStream());
    }

    @Override
    public void connect() throws IOException {
        mSocket = new Socket();
        mSocket.setKeepAlive(true);
        SocketAddress remoteAddr = new InetSocketAddress(hostIp, port) ;
        mSocket.connect(remoteAddr,connetTimeOut);
        KLog.d("connect()--->>> remoteAddr = "+remoteAddr.toString());
    }

    @Override
    public void setConnectTimeOut(int timeout) {
        if (timeout > 0) {
            connetTimeOut = timeout;
        }else {
            connetTimeOut = SOCKET_CONNECT_TIMEOUT_DEFAULT;
        }
    }

    @Override
    public boolean isAlive() {
        boolean isAlive = true;
        try {
            if (mSocket != null) {
                mSocket.sendUrgentData(0xff);
            }
        } catch (IOException e) {
            KLog.e(e.toString());
            isAlive = false;
        }
    	KLog.d("isAlive = "+isAlive);
        return isAlive;
    }

    @Override
    public void closeSocket() throws IOException {
        if (mSocket != null) {
            if (!mSocket.isClosed()) {
                if (getInputStream() != null) {
                    getInputStream().close();
                }
                if (getOutputStream() != null) {
                    getOutputStream().close();
                }
            }
            mSocket.close();
        }
    }
}
